<?php

namespace App\Jobs\Posts;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsWeightRefresh;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class UpdatePostWeightRefreshJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $currentDateTime = Carbon::now();
        WxPostsWeightRefresh::where('expect_time', '<=', $currentDateTime)
            ->where('status', 0)
            ->get()->map(function ($v){
                $the_post = WxPost::where('id', $v->post_id)->first();
                if($the_post){
                    DB::beginTransaction();
                    try {
                        // todo:
                        WxPost::withoutSyncingToSearch(function () use (&$v) {
                            WxPost::where('id', $v->post_id)->update(['weight'=>current_time()]);
                        });
                        WxPostsWeightRefresh::where('id', $v->id)->update([
                            'status' => 1,
                            'refresh_time' => current_time()
                        ]);
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    WxPostsWeightRefresh::where('id', $v->id)->delete();
                }
            });
    }
}
